﻿using System;

namespace unTroublemaker
{
    public abstract class SpecificationItemBase : ISpecificationItem
    {
        private RunStatus _status;

        protected SpecificationItemBase()
        {
            RunStatus = RunStatus.NotRun;
            ChildItems = new ISpecificationItem[]{};
        }

        public void Run()
        {
            StatusMessage = string.Empty;
            RunStatus = RunStatus.Running;

            try
            {
                RunStatus = RunTest() ? RunStatus.Passed : RunStatus.Failed;
            }
            catch (Exception e)
            {
                RunStatus = RunStatus.Failed;
                StatusMessage = "Exception occured:\r\n " + e.Format();
            }

            if (string.IsNullOrEmpty(StatusMessage))
                StatusMessage = RunStatus.ToString();
        }

        protected abstract bool RunTest();

        protected void SetResult(RunStatus runStatus, string message)
        {
            RunStatus = runStatus;
            StatusMessage = message;
        }

        public abstract string DisplayName { get; }

        public RunStatus RunStatus { get { return _status; }
        set
        {
            if (_status == value)
                return;

            var oldStatus = _status;
            _status = value;
            if (StatusChanged != null)
                StatusChanged(this, new StatusChangedEventArgs(value, oldStatus));

        }}
        
        public string StatusMessage { get; protected set; }

        public bool Passed { get { return RunStatus == RunStatus.Passed; } }

        public event StatusChangedEventHandler StatusChanged;

        public ISpecificationItem[] ChildItems { get; protected set; }
    }
}